import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Row, Col, Collapse, Card, Spin, message} from 'antd';
import routes from './routes';
import {FORM_BIG_OPTIONS, PAGE} from '../constants';
import {PERMISSION} from './constants';
import styles from './style.css';
import FileUpload from './FileUpload';
import ImagePreviewBtn from './ImagePreviewBtn';
import Return from '../common/Return';
const Panel = Collapse.Panel;
const EMPTY_ARRAY = [];
const bodyStyle = {
    padding: 0
};

import UsedPartDestoryDetail from './UsedPartDestoryDetail';
export class Add extends React.PureComponent {
    state = {
        loading: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    // eslint-disable-next-line react/sort-comp
    onChangeOrderUpload = data => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.updateAttachments(data);
    }
    openLoding = () => {
        this.setState({loading: true});
    }
    closeLoding = () => {
        this.setState({loading: false});
    }

    onSubmit = () => {
        const {attachments = []} = this.props.conditions;
        if(!attachments.length)
            return message.warn(this.props.intl.formatMessage({
                id: 'confirm.validate.message',
                defaultMessage: '附件清单不能为空'
            }));
        
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
 
    render() {
        const {details = EMPTY_ARRAY, attachments = EMPTY_ARRAY} = this.props.conditions;
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Card bodyStyle={bodyStyle}>
                        <Collapse defaultActiveKey="1" bordered={false}>
                            <Panel header={this.props.intl.formatMessage({
                                id: 'confirm.detail.panel',
                                defaultMessage: '销毁单详情'
                            })} key="1" forceRender>
                                <UsedPartDestoryDetail
                                    id={this.props.id}
                                    isDealerUser={this.props.isDealerUser}
                                    isConfirm={true}
                                    detail={this.props.conditions}
                                    openLoding={this.openLoding}
                                    closeLoding={this.closeLoding}
                                    loading={this.state.loading}/>
                            </Panel>
                        </Collapse>
                    </Card>
                    <Card
                        extra={<ImagePreviewBtn attachments={attachments} />}
                        title={this.props.intl.formatMessage({
                            id: 'confirm.card.fileList.title',
                            defaultMessage: '附件清单'
                        })}>
                        <Row>
                            <Col {...FORM_BIG_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeOrderUpload} onRemove={this.props.removeAttachments} fileList={attachments} />
                            </Col>
                        </Row>
                    </Card>
                    {this.props.submitable && (
                        <Card type="inner">
                            <Row>
                                <Col className="col-align-right">
                                    <Button
                                        key="submit"
                                        loading={this.state.loading}
                                        onClick={this.onSubmit}
                                        type="primary">
                                        {this.props.intl.formatMessage({
                                            id: 'confirm.btn.submit',
                                            defaultMessage: '提交'
                                        })}
                                    </Button>
                                </Col>
                            </Row>
                        </Card>
                    )}
                </Spin>
                
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onClickConfirm,
    updateAttachments,
    removeAttachments,
    getDetail,
} from './actions';
import {createSelector} from 'reselect';

const getSubmitData = createSelector(
    state => state.getIn(['page', 'appState', 'submitData']),
    data => {
        const conditions = data.toJS() || {};
        return conditions;
    }
);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        return data.includes(PERMISSION.confirm) && options.includes(PERMISSION.confirm);
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: () =>
        dispatch(onClickConfirm(ownProps.id)).then(success => {
            if(success) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return success;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    updateAttachments: data => dispatch(updateAttachments(data)),
    removeAttachments: ({id}) => dispatch(removeAttachments(id)),
    onUmount: () => dispatch(clearData()),
});


export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
